﻿/* Copyright (c) Microsoft Corporation
 * 
 * All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
 * 
 * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Windows;

namespace ProximityTapper
{
    class UdpNfcSimBroadcastListener
    {
        public void Start()
        {
            try
            {
                foreach (var net in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                {
                    var address = (from a in net.GetIPProperties().UnicastAddresses
                                   where a.Address.AddressFamily == AddressFamily.InterNetwork
                                   select a).FirstOrDefault();
                    if (address != null)
                    {
                        try
                        {
                            var udpClient = new UdpClient(new System.Net.IPEndPoint(address.Address, 9299));
                            udpClient.EnableBroadcast = true;
                            StartUdpClientListen(udpClient);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Exception while starting UDP listener on adapter " + (net.Name ?? "") + " (" + (net.Description ?? "") + " - " + address.ToString() + "), ensure no other applications are running that are listening for UDP on port 9299.\r\n\r\n" + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception while starting UDP listener, ensure no other applications are running that are listening for UDP on port 9299.\r\n" + ex.ToString());
            }
        }

        public delegate void DeviceDiscoveredDelegate(ProximityDeviceConnectInfo found);
        public event DeviceDiscoveredDelegate DeviceDiscovered;

        private void StartUdpClientListen(UdpClient udpClient)
        {
            udpClient.BeginReceive((res) =>
            {
                System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 9299);
                var data = udpClient.EndReceive(res, ref ep);
                if (res.IsCompleted)
                {
                    var found = new ProximityDeviceConnectInfo(data, ep);

                    if (DeviceDiscovered != null)
                    {
                        DeviceDiscovered(found);
                    }
                }
                StartUdpClientListen(udpClient);
            }, null);
        }
    }
}
